package apps.hackstermia.buttonthings;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.util.Set;

public class BleActivity extends Activity {
    private static BluetoothDevice remoteDevice = null;
    private static final boolean D = true;
    public static String EXTRA_DEVICE_ADDRESS = "device_address";
    private static final String TAG = "DeviceListActivity";
    private BluetoothAdapter mBtAdapter;
    private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View v, int arg2, long arg3) {
            BleActivity.this.mBtAdapter.cancelDiscovery();
            String info = ((TextView) v).getText().toString();
            if (info.length() >= 17) {
                String address = info.substring(info.length() - 17);

                BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
                if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                    Log.d(TAG, device.getName());

                    Log.d(TAG, address);

                    if (device.getBondState() != BluetoothDevice.BOND_BONDED) {

                        //开始配对
                        try{
                            ClsUtils.createBond(device.getClass(),device);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
//                        break;
//                        try {
//                            Log.d("mylog", "NOT BOND_BONDED");
//                            ClsUtils.setPin(device.getClass(), device, "1234"); // 手机和蓝牙采集器配对
//                            ClsUtils.createBond(device.getClass(), device);
//                            //    ClsUtils.cancelPairingUserInput(device.getClass(), device);
//                            remoteDevice = device; // 配对完毕就把这个设备对象传给全局的remoteDevice
//
//                        } catch (Exception e) {
//                            // TODO Auto-generated catch block
//                            Log.d("mylog", "setPiN failed!");
//                            e.printStackTrace();
//                        } //

                    } else {
                        Log.d("mylog", "HAS BOND_BONDED");
                        try {
                            //ClsUtils这个类的的以下静态方法都是通过反射机制得到需要的方法
                            ClsUtils.createBond(device.getClass(), device);//创建绑定
                            ClsUtils.setPin(device.getClass(), device, "1234"); // 手机和蓝牙采集器配对
                            ClsUtils.createBond(device.getClass(), device);
                            //    ClsUtils.cancelPairingUserInput(device.getClass(), device);
                            remoteDevice = device; // 如果绑定成功，就直接把这个设备对象传给全局的remoteDevice
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            Log.d("mylog", "setPiN failed!");
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
    };

    private ArrayAdapter<String> mNewDevicesArrayAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("android.bluetooth.device.action.FOUND".equals(action)) {
                BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                if (BleActivity.this.mNewDevicesArrayAdapter.getPosition(device.getName() + "\n" + device.getAddress()) == -1) {
                    BleActivity.this.mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            } else if ("android.bluetooth.adapter.action.DISCOVERY_FINISHED".equals(action)) {
                BleActivity.this.setProgressBarIndeterminateVisibility(false);
                BleActivity.this.setTitle(R.string.select_device);
                if (BleActivity.this.mNewDevicesArrayAdapter.getCount() == 0) {
//                    BleActivity.this.mNewDevicesArrayAdapter.add(BleActivity.this.getResources().getText(R.string.none_found).toString());
                }
                BleActivity.this.findViewById(R.id.button_scan).setVisibility(View.VISIBLE);
            }else if(action.equals("android.bluetooth.device.action.PAIRING_REQUEST")) //再次得到的action，会等于PAIRING_REQUEST
            {
                Log.d(TAG, "aaaaaaaaaa");
                Log.e("action2=", action);

//                if(btDevice.getName().contains("lmln_bale_car"))
//                {
//                    Log.e("here", "OKOKOK");
//
//                    try {
//
//                        //1.确认配对
//                        ClsUtils.setPairingConfirmation(btDevice.getClass(), btDevice, true);
//                        //2.终止有序广播
//                        Log.i("order...", "isOrderedBroadcast:"+isOrderedBroadcast()+",isInitialStickyBroadcast:"+isInitialStickyBroadcast());
//                        abortBroadcast();//如果没有将广播终止，则会出现一个一闪而过的配对框。
//                        //3.调用setPin方法进行配对...
//                        boolean ret = ClsUtils.setPin(btDevice.getClass(), btDevice, pin);
//                        Log.d("BluetoothReceiver", "ret:" + ret);
//
//                    } catch (Exception e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//                }else
//                    Log.e("提示信息", "这个设备不是目标蓝牙设备");

            }
        }
    };
    private ListView newDevicesListView;
    private ListView pairedListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(5);
        setContentView(R.layout.devicelist);
        setResult(0);
        ((Button) findViewById(R.id.button_scan)).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                BleActivity.this.doDiscovery();
                v.setVisibility(View.GONE);
                BleActivity.this.pairedListView.setVisibility(View.GONE);
            }
        });
        this.mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name);
        this.mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name);
        this.pairedListView = (ListView) findViewById(R.id.paired_devices);
        this.pairedListView.setAdapter(this.mPairedDevicesArrayAdapter);
        this.pairedListView.setOnItemClickListener(this.mDeviceClickListener);
        this.newDevicesListView = (ListView) findViewById(R.id.new_devices);
        this.newDevicesListView.setAdapter(this.mNewDevicesArrayAdapter);
        this.newDevicesListView.setOnItemClickListener(this.mDeviceClickListener);

        registerReceiver(this.mReceiver, new IntentFilter("android.bluetooth.device.action.FOUND"));
        registerReceiver(this.mReceiver, new IntentFilter("android.bluetooth.adapter.action.DISCOVERY_FINISHED"));
        this.mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = this.mBtAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices) {
                this.mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        } else {
            this.mPairedDevicesArrayAdapter.add(getResources().getText(R.string.none_paired).toString());
        }

        pairedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
                for (BluetoothDevice device : pairedDevices) {
                    try {
                        ClsUtils.cancelBondProcess(device.getClass(), device);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    unpairDevice(device);
                }
            }
        });
        if (ActivityCompat.checkSelfPermission(this, "android.permission.ACCESS_FINE_LOCATION") != 0) {
            ActivityCompat.requestPermissions(this, new String[]{"android.permission.ACCESS_FINE_LOCATION"}, 1);
        } else if (ActivityCompat.checkSelfPermission(this, "android.permission.ACCESS_COARSE_LOCATION") != 0) {
            ActivityCompat.requestPermissions(this, new String[]{"android.permission.ACCESS_COARSE_LOCATION"}, 2);
        }
    }

    private static void unpairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass().getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    @SuppressLint("WrongConstant")
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case 1 /*1*/:
//                if (grantResults.length <= 0 || grantResults[0] != 0) {
//                    Toast.makeText(this, "app没有定位权限将无法搜索蓝牙设备!", 1);
//                    return;
//                }
//                return;
//            case 2 /*2*/:
//                if (grantResults.length <= 0 || grantResults[0] != 0) {
//                    Toast.makeText(this, "app没有定位权限将无法搜索蓝牙设备!", 1);
//                    return;
//                }
//                return;
//            default:
//                return;
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (this.mBtAdapter != null) {
            this.mBtAdapter.cancelDiscovery();
        }
        unregisterReceiver(this.mReceiver);
    }

    private void doDiscovery() {
        Log.d(TAG, "doDiscovery()");
        setProgressBarIndeterminateVisibility(D);
        setTitle(R.string.scanning);
        findViewById(R.id.title_paired_devices).setVisibility(View.GONE);
        findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
        if (this.mBtAdapter.isDiscovering()) {
            this.mBtAdapter.cancelDiscovery();
        }
        this.mNewDevicesArrayAdapter.clear();
        this.mNewDevicesArrayAdapter.notifyDataSetChanged();
        this.mBtAdapter.startDiscovery();
    }
}

